package com.hyou.sc.eureka.client.auth.module.login;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.hyou.sc.eureka.client.auth.config.JwtProp;
import com.hyou.sc.eureka.client.auth.consts.UserStatus;
import com.hyou.sc.eureka.client.auth.dto.form.LoginForm;
import com.hyou.sc.eureka.client.auth.dto.pojo.UserDO;
import com.hyou.sc.eureka.client.auth.dto.vo.LoginVO;
import com.hyou.sc.eureka.client.auth.service.base.itfc.UserService;
import com.hyou.springboot.annotation.FormValidator;
import com.hyou.springboot.base.ResponseMessage;
import com.hyou.springboot.util.JwtUtil;
import com.hyou.springboot.util.ResponseMessageUtil;

@RestController("loginController")
public class LoginController {
    
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    
    @Resource(name = "jwtProp")
    private JwtProp jwtProp;
    
    @Resource(name = "userService")
    private UserService userService;
    
    @FormValidator
    @PostMapping(path = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseMessage<LoginVO> login(@RequestBody LoginForm form) {
        log.debug("param LoginForm : {}", form);
        
        UserDO paramBean = new UserDO();
        paramBean.setAccount(form.getAccount());
        
        String accountToSign = form.getAccount() + form.getPasswd();
        String md5Pwd = DigestUtils.md5DigestAsHex(accountToSign.getBytes(StandardCharsets.UTF_8));
        paramBean.setPasswd(md5Pwd);
        
        paramBean.setStatus(UserStatus.ON);
        
        List<UserDO> userList = userService.listByConditions(paramBean);
        
        if (CollectionUtils.isEmpty(userList)) {
            return ResponseMessageUtil.genFailResult("用户不存在");
        }
        
        UserDO user = userList.get(0);
        
        if (UserStatus.OFF.equals(user.getStatus())) {
            return ResponseMessageUtil.genFailResult("账号已被禁用");
        }
        
        // 登录成功，生成Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("uid", String.valueOf(user.getId()));
        String token = JwtUtil.createJwtToken(claims, jwtProp.getSecretKey(), jwtProp.getExpirationSeconds());
        
        LoginVO data = new LoginVO();
        data.setToken(token);
        return ResponseMessageUtil.genSuccessResult(data);
    }
    
}
